package com.sanjin.listener;

import com.sanjin.entity.WxMiniUser;
import com.sanjin.exception.MyException;
import com.sanjin.repository.WxMiniUserRepository;
import com.sanjin.service.WxMiniUserService;
import com.sanjin.utils.JwtUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description: 监听 SpringBoot 启动，加载一个小程序用户用于测试
 * @author: sanjin
 * @date: 2019/5/15 16:48
 */
@Component
@Log4j
public class LoadWxMiniUserListener  implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private WxMiniUserRepository wxMiniUserRepository;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 初始化一个 微信小程序用户的 token
        List<WxMiniUser> all = wxMiniUserRepository.findAll();
        if (all.size() <= 0)
            throw new MyException("没有微信小程序用户");
        WxMiniUser wxMiniUser = all.get(0);

        // 生产token
        String token = jwtUtils.generateToken(wxMiniUser);

        log.info("【创建微信小程序用户token】");
        log.info(wxMiniUser);
        log.info("【token值】: " + token);
    }
}
